//
//  NSObject+WLCache.m
//  xiacai
//
//  Created by 专注 on 2017/12/27.
//  Copyright © 2017年 TBS. All rights reserved.
//

#import "NSFileManager+WLCache.h"
#import <CommonCrypto/CommonDigest.h>
#import "NSFileManager+WLExtension.h"

#define isMd5Name NO

@implementation NSFileManager (WLCache)

/** 读取数据 */
+ (id)readKey_wl:(NSString *)keys
      folderName:(NSString *)folderName
        dataType:(dataType_wl)type{
    id cacheData = nil;
    /** 拼接文件路径 */
    NSString *path = [self readKeyForPath_wl:keys folderName:folderName dataType:type];
    if (!path){
        return nil;
    }
    /** 创建 文件管理 */
    NSFileManager *fileManager = [NSFileManager defaultManager];
    /** 读取文件 数据 */
    NSData *data = [fileManager contentsAtPath:path];
    if (data) {
        cacheData = data;
        NSLog(@"读取缓存数据%@",path);
        switch (type) {
            case imageData_wl:
                return [UIImage imageWithData:cacheData];
                break;
            case jsonData_wl:
                return [NSJSONSerialization JSONObjectWithData:cacheData options:NSJSONReadingMutableLeaves error:nil];
                break;
            case defaultData_wl:
            default:
                break;
        }
    }
    return nil;
}
/** 缓存数据 */
+ (NSString *)saveData_wl:(id)saveData
                key:(NSString *)keys
         folderName:(NSString *)folderName
           dataType:(dataType_wl)type{
    //    判断是否有标示
    if (!keys) {NSLog(@"没有文件标示"); return nil;}
    //    判断数据是否为空
    if (!saveData) {NSLog(@"没有缓存文件"); return nil;}
    //    判断数据是否为空对象
    if ([saveData isKindOfClass:[NSNull class]]) {NSLog(@"缓存文件为空对象"); return nil;}
    /** 拼接文件路径 */
    NSString *path = [self keyForPath_wl:keys folderName:folderName dataType:type];
    //    创建空数据 开始处理数据
    NSData *data = nil;
    //    基本区分数据
    switch (type) {
        case imageData_wl://图片数据
            if ([saveData isKindOfClass:[NSData class]]) {
                data = saveData;
            } else {
                data = UIImagePNGRepresentation(saveData);;
            }
            break;
        case jsonData_wl://json数据
            if ([saveData isKindOfClass:[NSData class]]) {
                data = saveData;
            } else {
                data = [self objToData:saveData];
            }
            break;
        case defaultData_wl://data
        default://默认数据 data 格式
            if ([saveData isKindOfClass:[NSData class]]) {
                data = saveData;
            }
            else{
                NSLog(@"请传入data数据！");
            }
            break;
    }
    //    判断数据是否为空
    if (!data) {NSLog(@"缓存文件格式错误！"); return nil;}
    //    保存数据
    BOOL isOk = [[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:nil];
    if (isOk) {
        NSLog(@"保存成功");
        return path;
    } else {
        NSLog(@"保存失败");
        return nil;
    }
    return nil;
}


/** 读取数据路径 */
+ (NSString *)readKeyForPath_wl:(NSString *)keys
                     folderName:(NSString *)folderName
                       dataType:(dataType_wl)type{
    /** 拼接文件路径 */
    NSString *path = [self keyForPath_wl:keys folderName:folderName dataType:type];
    /** 判断文件是否存在 */
    if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:nil]){
        return path;
    }
    return nil;
}
/** 获取完整路径 */
+ (NSString *)keyForPath_wl:(NSString *)keys
                 folderName:(NSString *)folderName
                   dataType:(dataType_wl)type{
    NSString *key = [NSFileManager md5_string:keys type:type];
    if (!keys) {return nil;}
    /** 获取缓存目录 */
    NSString *directoryPath = [NSFileManager wl_createFolderName:folderName];
    /** 拼接文件路径 */
    NSString *path = [directoryPath stringByAppendingPathComponent:key];
    return path;
}


/** 对象转数据 */
+ (NSData *)objToData:(id)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        return nil;
    }
    return jsonData;
}
+ (NSString *)md5_string:(NSString *)string type:(dataType_wl)type{
    if (isMd5Name){
        //    NSString *string = [self copy];
        if (string == nil || [string length] == 0) {
            return nil;
        }
        unsigned char digest[CC_MD5_DIGEST_LENGTH], i;
        CC_MD5([string UTF8String], (int)[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding], digest);
        NSMutableString *ms = [NSMutableString string];
        
        for (i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
            [ms appendFormat:@"%02x", (int)(digest[i])];
        }
        NSString *name = [ms copy];
        
        switch (type) {
            case imageData_wl:
                name = [NSString stringWithFormat:@"%@.%@",name,@"image"];
                break;
            case jsonData_wl:
                name = [NSString stringWithFormat:@"%@.%@",name,@"json"];
                break;
            case defaultData_wl:
            default:
                break;
        }
        return name;
    }
    return string;
}
+ (BOOL)isSameDay:(NSDate *)anotherDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components1 = [calendar components:(NSCalendarUnitYear
                                                          | NSCalendarUnitMonth
                                                          | NSCalendarUnitDay)
                                                fromDate:[NSDate new]];
    NSDateComponents *components2 = [calendar components:(NSCalendarUnitYear
                                                          | NSCalendarUnitMonth
                                                          | NSCalendarUnitDay)
                                                fromDate:anotherDate];
    return ([components1 year] == [components2 year]
            && [components1 month] == [components2 month]
            && [components1 day] == [components2 day]);
}


@end

